package cn.csc.module.shoppingCard.controller.app.card;

import cn.csc.framework.common.pojo.CommonResult;
import cn.csc.framework.security.core.util.SecurityFrameworkUtils;
import cn.csc.module.shoppingCard.controller.admin.card.vo.CardRespVO;
import cn.csc.module.shoppingCard.controller.app.card.vo.AppCardActivateReqVO;
import cn.csc.module.shoppingCard.convert.card.CardConvert;
import cn.csc.module.shoppingCard.dal.dataobject.card.CardDO;
import cn.csc.module.shoppingCard.service.card.CardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.List;

import static cn.csc.framework.common.pojo.CommonResult.success;

@Api(tags = "用户APP - 购物卡")
@RestController
@RequestMapping("/shoppingCard/card")
@Validated
public class AppCardController {

    @Resource
    private CardService cardService;


    @GetMapping("/get")
    @ApiOperation("通过主键ID获得购物卡信息")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1892443252514313531", dataTypeClass = BigInteger.class)
    public CommonResult<CardRespVO> getCard(@RequestParam("id") BigInteger id) {
        CardDO card = cardService.getCard(id);
        CardRespVO respVO = CardConvert.INSTANCE.convert(card);
        if (LocalDateTime.now().isAfter(respVO.getExpireTime())){
            respVO.setExpired(true);
        }
        return success(respVO);
    }

    /**
     * 获取当前用户的购物卡信息
     */
    @GetMapping("/getByUserId")
    @ApiOperation("获取当前用户的购物卡信息")
    public CommonResult<List<CardRespVO>> getByUserId() {
        List<CardDO> cards = cardService.selectListByUserId(BigInteger.valueOf(SecurityFrameworkUtils.getLoginUserId()));
        List<CardRespVO> respVOS = CardConvert.INSTANCE.convertList(cards);
        respVOS.forEach(c -> {
            if (LocalDateTime.now().isAfter(c.getExpireTime())){
                c.setExpired(true);
            }
        });
        return success(respVOS);
    }

    /**
     * 激活购物卡
     */
    @PutMapping("/activate")
    @ApiOperation("激活购物卡")
    public CommonResult<BigInteger> activate(@Valid @RequestBody AppCardActivateReqVO reqVO) {
        return success(cardService.activate(reqVO));
    }


}
